<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ZT数据</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/bootstrap-icons.css" rel="stylesheet">
    <style>
        .search-form {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .result-table {
            background: white;
            border-radius: 10px;
            font-size: 13px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }


        /* 名字列宽度设置 */
        .result-table th:nth-child(1),
        .result-table td:nth-child(1) {
            min-width: 10px;
            width: 10px;
        }

        .result-table th,
        .result-table td {
            border: 1px solid #ddd;  /* 细线边框 */
            padding: 8px;
        }

        /*!* 名字列宽度设置 *!*/
        /*.result-table th:nth-child(3),*/
        /*.result-table td:nth-child(3) {*/
        /*    min-width: 80px;*/
        /*    width: 80px;*/
        /*}*/

        .table th {
            background: #e9ecef;
            border-top: none;
            font-weight: 600;
        }
        .pagination-info {
            color: #6c757d;
            font-size: 12px;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        .no-data {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        .btn-search {
            background: linear-gradient(45deg, #007bff, #0056b3);
            border: none;
            color: white;
            font-weight: 500;
        }
        .btn-search:hover {
            background: linear-gradient(45deg, #0056b3, #004085);
            color: white;
        }
        .btn-reset {
            background: #6c757d;
            border: none;
            color: white;
        }
        .btn-reset:hover {
            background: #5a6268;
            color: white;
        }
        .stock-code {
            font-family: 'Courier New', monospace;
            font-weight: bold;
            color: #007bff;
        }
        .stock-name {
            font-weight: 500;
            color: #495057;
        }
        .price-positive {
            color: #dc3545;
            font-weight: bold;
        }
        .price-negative {
            color: #28a745;
            font-weight: bold;
        }
        .limit-up-type {
            background: #e7f3ff;
            color: #0066cc;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 500;
        }
        .consecutive-days {
            background: #fff3cd;
            color: #856404;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 500;
        }
        .summary-section {
            margin-bottom: 20px;
        }
        .summary-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }
        .summary-item:hover {
            background: #e9ecef;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .summary-item.clickable {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .summary-item.clickable:hover {
            background: #d1ecf1;
            border-color: #bee5eb;
        }
        .summary-item.clickable:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .summary-reason {
            font-weight: 600;
            color: #495057;
            margin-bottom: 5px;
            font-size: 12px;
        }
        .summary-count {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
        }
        .summary-percentage {
            font-size: 12px;
            color: #6c757d;
            margin-left: 5px;
        }
        .total-summary {
            background: linear-gradient(45deg, #007bff, #0056b3);
            color: white;
            border: none;
        }
        .total-summary:hover {
            background: linear-gradient(45deg, #0056b3, #004085);
        }
        .total-summary.clickable:hover {
            background: linear-gradient(45deg, #0056b3, #004085);
            border-color: transparent;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        .total-summary .summary-reason {
            color: white;
        }
        .total-summary .summary-count {
            color: white;
        }
        .total-summary .summary-percentage {
            color: rgba(255,255,255,0.8);
        }

        /* 每日汇总样式 */
        .daily-summary-section {
            margin-bottom: 20px;
        }
        .daily-summary-container {
            display: flex;
            overflow-x: auto;
            padding: 15px 0;
            gap: 12px;
            scroll-behavior: smooth;
        }
        .daily-summary-container::-webkit-scrollbar {
            height: 6px;
        }
        .daily-summary-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        .daily-summary-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        .daily-summary-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        .daily-summary-item {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 10px;
            flex-shrink: 0;
            box-shadow: 0 3px 6px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            overflow: hidden;
        }
        .daily-summary-item:hover {
            box-shadow: 0 6px 12px rgba(0,0,0,0.15);
            transform: translateY(-1px);
        }
        /* 响应式宽度 */
        .daily-summary-item.auto-width {
            min-width: 0;
        }
        .daily-summary-item.fixed-width {
            min-width: 200px;
            max-width: 220px;
        }
        /* 大屏幕：7天完全显示 */
        @media (min-width: 1200px) {
            .daily-summary-item.auto-width {
                flex: 1;
                max-width: calc((100% - 72px) / 7); /* 6个间距 * 12px = 72px */
                min-width: 150px;
            }
        }
        /* 中等屏幕：5天显示 */
        @media (min-width: 768px) and (max-width: 1199px) {
            .daily-summary-item.auto-width {
                flex: 1;
                max-width: calc((100% - 48px) / 5); /* 4个间距 * 12px = 48px */
                min-width: 140px;
            }
        }
        /* 小屏幕：3天显示 */
        @media (max-width: 767px) {
            .daily-summary-item.auto-width {
                flex: 1;
                max-width: calc((100% - 24px) / 3); /* 2个间距 * 12px = 24px */
                min-width: 120px;
            }
        }
        .daily-summary-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        .daily-summary-header:hover {
            background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
        }
        .daily-summary-header.today {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        }
        .daily-summary-header.today:hover {
            background: linear-gradient(135deg, #0f8a7e 0%, #32d96b 100%);
        }
        .daily-summary-date {
            font-size: 12px;
            font-weight: 700;
            margin-bottom: 6px;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
            line-height: 1.2;
        }
        .daily-summary-stats {
            font-size: 12px;
            opacity: 0.9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .daily-summary-content {
            padding: 0;
            max-height: 0;
            overflow: hidden;
            transition: all 0.3s ease;
        }
        .daily-summary-content.show {
            max-height: 400px;
            overflow-y: auto;
        }
        .daily-summary-content::-webkit-scrollbar {
            width: 4px;
        }
        .daily-summary-content::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        .daily-summary-content::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 2px;
        }
        .daily-reason-item {
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 8px 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .daily-reason-item:hover {
            background: #e9ecef;
        }
        .daily-reason-item:last-child {
            border-bottom: none;
        }
        .daily-reason-text {
            flex: 1;
            font-weight: 500;
            color: #495057;
            font-size: 11px;
            line-height: 1.3;
            margin-right: 6px;
            word-break: break-word;
        }
        .daily-reason-count {
            background: #007bff;
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 10px;
            font-weight: 600;
            white-space: nowrap;
            min-width: 20px;
            text-align: center;
        }
        .expand-icon {
            transition: transform 0.3s ease;
        }
        .expand-icon.rotated {
            transform: rotate(180deg);
        }

        .text-red {
            color: red; /* 红色 */
        }
        .text-green {
            color: green; /* 绿色 */
        }

        /* 排序样式 */
        .sortable {
            cursor: pointer;
            user-select: none;
            position: relative;
        }
        .sortable:hover {
            background-color: #f8f9fa;
        }
        .sort-icon {
            margin-left: 5px;
            opacity: 0.3;
            font-size: 12px;
        }
        .sort-icon::before {
            content: "↕";
        }
        .sortable.sort-asc .sort-icon {
            opacity: 1;
            color: #007bff;
        }
        .sortable.sort-asc .sort-icon::before {
            content: "↑";
        }
        .sortable.sort-desc .sort-icon {
            opacity: 1;
            color: #007bff;
        }
        .sortable.sort-desc .sort-icon::before {
            content: "↓";
        }

        /* 添加标黄高亮样式 */
        .daily-reason-item.highlighted .daily-reason-text {
            background-color: yellow;
            padding: 2px 4px;
            border-radius: 3px;
            transition: background-color 0.3s ease;
        }

    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <h2 class="mb-4">
                    <i class="bi bi-graph-up-arrow text-danger"></i>
                    涨停数据查询
                <a href="/" class="btn btn-outline-primary btn-sm float-right">返回主页</a>
                <a href="/analysis" class="btn btn-outline-primary btn-sm float-right">数据分析</a>
                <a href="/gainian" class="btn btn-outline-primary btn-sm float-right">资金流向</a>
                <a href="/stocksflow" class="btn btn-outline-primary btn-sm float-right">个股资金</a>
                </h2>
                <!-- 查询表单 -->
                <div class="search-form">
                    <form id="searchForm">
                        <div class="row g-1">
                            <div class="col-md-1">
                                <label for="startDate" class="form-label">开始日期</label>
                                <input type="date" class="form-control" id="startDate" name="startDate">
                            </div>
                            <div class="col-md-1">
                                <label for="endDate" class="form-label">结束日期</label>
                                <input type="date" class="form-control" id="endDate" name="endDate">
                            </div>
                            <div class="col-md-3">
                                <label for="stockCodeOrName" class="form-label">股票代码/名称 =关注 +自选</label>
                                <input type="text" class="form-control" id="stockCodeOrName" name="stockCodeOrName"
                                       placeholder="输入股票代码或名称">
                            </div>
                            <div class="col-md-3">
                                <label for="gainian" class="form-label">板块概念 =关注</label>
                                <input type="text" class="form-control" id="gainian" name="gainian" placeholder="板块概念">
                            </div>
                            <div class="col-md-1">
                                <label for="consecutiveDays" class="form-label">几天几板</label>
                                <select class="form-select" id="consecutiveDays" name="consecutiveDays">
                                    <option value="">全部</option>
                                </select>
                            </div>
                            <div class="col-md-1">
                                <label for="limitUpType" class="form-label">涨停类型</label>
                                <select class="form-select" id="limitUpType" name="limitUpType">
                                    <option value="">全部</option>
                                </select>
                            </div>
                            <div class="col-md-1">
                                <label for="pageSize" class="form-label">每页显示</label>
                                <select class="form-select" id="pageSize" name="pageSize">
                                    <option value="20">20条</option>
                                    <option value="50">50条</option>
                                    <option value="100">100条</option>
                                    <option value="500" selected>500条</option>
                                </select>
                            </div>
                        </div>
                        <div class="row g-3 mt-2">

                            <div class="col-md-6 d-flex align-items-end">
                                <button type="submit" class="btn btn-search me-2">
                                    <i class="bi bi-search"></i> 查询
                                </button>
                                <button type="button" class="btn btn-reset me-2" onclick="resetForm()">
                                    <i class="bi bi-arrow-clockwise"></i> 重置
                                </button>
                                <button type="button" class="btn btn-success" onclick="getTodayData()">
                                    <i class="bi bi-calendar-day"></i> 今日涨停
                                </button>
                                <button type="button" class="btn btn-info ms-2" onclick="getDailySummary()">
                                    <i class="bi bi-calendar3"></i> 每日汇总
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- 汇总统计 -->
                <div class="summary-section" id="summarySection" style="display: none;">
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center"
                                     style="cursor: pointer;" onclick="toggleSummary()">
                                    <h5 class="mb-0">
                                        <i class="bi bi-bar-chart-fill"></i>
                                        涨停原因统计
                                    </h5>
                                    <i class="bi bi-chevron-up" id="summaryToggleIcon"></i>
                                </div>
<!--                                <div class="card-body" id="summaryBody">-->
<!--                                    <div class="row" id="summaryContent">-->
<!--                                        &lt;!&ndash; 统计内容将通过JavaScript动态生成 &ndash;&gt;-->
<!--                                    </div>-->
<!--                                </div>-->
                            </div>
                        </div>
                    </div>
                </div>


                <div class="input-group">
                    <!-- 将textarea改为div以支持HTML渲染 -->
                    <div class="form-control"
                         id="allHOTGainian" rows="4" readonly style="background-color: #f8f9fa;   min-height: 100px;  padding: 0.375rem 0.75rem; white-space: normal; word-wrap: break-word;font-size: 13px;"
                         placeholder="概念汇总">
                    </div>
                </div>

                <!-- 每日汇总 -->
                <div class="daily-summary-section" id="dailySummarySection" style="display: none;min-height: 600px;">
                    <div class="card-header bg-info text-white d-flex justify-content-between align-items-center"
                         style="cursor: pointer;" onclick="toggleDailySummarySection()">
                        <h5 class="mb-0">
                            <i class="bi bi-calendar3"></i>
                            每日涨停原因汇总
                        </h5>
                        <i class="bi bi-chevron-up" id="dailySummaryToggleIcon"></i>
                    </div>
                    <div class="card-body" id="dailySummaryBody" style="min-height: 550px; padding: 1.5rem;">
                        <div class="daily-summary-container" id="dailySummaryContent" style="min-height: calc(100% - 30px);">
                            <!-- 每日汇总内容将通过JavaScript动态生成 -->
                        </div>
                    </div>
                </div>


                <div class="col-md-6 d-flex align-items-end">
                    <button type="button" class="btn btn-success" id="addSelectStock" onclick="addupdateFocusStocks()">
                        <i class="bi bi-calendar-day"></i> 关注
                    </button>
                    <button type="button" class="btn btn-info ms-2" id="remSelectStock" onclick="removeupdateFocusStock()">
                        <i class="bi bi-calendar3"></i> 取注
                    </button>
                    <button type="button" class="btn btn-success" id="alllimtStock" onclick="copyallstock()">
                        <i class="bi bi-calendar-day"></i> 复制所有
                    </button>
                    <button type="button" class="btn btn-info ms-2" id="SelectStock" onclick="getSelectedStockCodesJQ()">
                        <i class="bi bi-calendar3"></i> 复制选择
                    </button>
                </div>


                <!-- 结果表格 -->
                <div class="result-table">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead>
                                <tr>
                                    <th class="px-2 py-2 text-xs font-medium text-gray-500 w-16" style="width: 28px;" >
                                        <input type="checkbox" id="select-all" class="select-all">
                                    </th>

                                    <th class="sortable" data-sort="stockCode">代码<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="stockName">名称<span class="sort-icon"></span></th>
<!--                                    <th>现价</th>-->
                                    <th class="sortable" data-sort="currentPrice">现价<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="priceIncreasePercent">涨幅(%)<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="firstLimitUpTime">首次涨停<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="finalLimitUpTime">最终涨停<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="limitUpReason">涨停原因<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="gainians">概念<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="limitUpOrderVolume">封单(万手)<span class="sort-icon"></span></th>
                                    <th>封金额(亿)</th>
                                    <th>封成比(%)</th>
                                    <th>封流比(%)</th>
                                    <th>开板</th>
                                    <th class="sortable" data-sort="consecutiveLimitUpCount">几天几板<span class="sort-icon"></span></th>
<!--                                    <th>几天几板</th>-->
                                    <th class="sortable" data-sort="consecutiveLimitUpDays">连板<span class="sort-icon"></span></th>
                                    <th class="sortable" data-sort="limitUpType">涨停类型<span class="sort-icon"></span></th>
                                    <th>记录时间</th>
                                    <th class="sortable" data-sort="rankPosition">热度(今昨差)<span class="sort-icon"></span></th>
<!--                                    <th class="sortable" data-sort="mainCapitalFlow">资金(主|全)<span class="sort-icon"></span></th>-->
                                </tr>
                            </thead>
                            <tbody id="dataTableBody">
                                <tr>
                                    <td colspan="19" class="loading">
                                        <i class="bi bi-hourglass-split"></i> 请输入查询条件并点击查询
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页信息和控件 -->
                    <div class="d-flex justify-content-between align-items-center p-3" id="paginationContainer" style="display: none !important;">
                        <div class="pagination-info" id="paginationInfo"></div>
                        <nav>
                            <ul class="pagination mb-0" id="pagination"></ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/js/jquery.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 0;
        let totalPages = 0;
        let totalElements = 0;
        let flowStock = '';
        let revGainian = '';
        let allOptional = '';
        let flowGainian = '';
        let currentData = []; // 存储当前数据用于排序
        let currentSort = { field: null, direction: null }; // 当前排序状态



        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeSelects();
            setDefaultDates();
            initializeSorting();
            initRealTimeSearch();

            getDailySummary();
            getTodayData();
            // 全选复选框事件
            document.getElementById('select-all').addEventListener('click', setupCheckboxHandler);
        });

        // 1. 首先修改openSelectedStockCodesJQ函数，支持传入单个代码
        function openSelectedStockCodes(selectedCode) {
            let selectedCodes;

            // 如果有传入单个代码，则直接使用该代码
            if (selectedCode) {
                selectedCodes = [selectedCode];
            } else {
                // 否则获取所有选中的代码（保持原逻辑）
                // selectedCodes = $('input[name="select-stockCode"]:checked').map(function() {
                //     return $(this).val();
                // }).get();
            }

            // 处理未选中的情况
            if (selectedCodes.length === 0) {
                alert('请先选择股票');
                return;
            }

            // 拼接股票代码为参数（多个代码用逗号分隔）
            // const codeParam = ""+selectedCodes.join(',');

            // 构建基于根目录的相对路径
            const targetUrl = `/stocksflow/summarystock?code=`+selectedCodes;
            console.log("selectedCode==="+selectedCode+"====targetUrl==="+targetUrl);
            // 在新标签页打开目标地址
            window.open(targetUrl, '_blank');
        }

        // 初始化实时搜索
        function initRealTimeSearch() {
            const stockInput = document.getElementById('stockCodeOrName');
            const gainianInput = document.getElementById('gainian');

            // 为两个输入框绑定输入事件
            stockInput.addEventListener('input', handleRealTimeSearch);
            gainianInput.addEventListener('input', handleRealTimeSearch);
        }

        // 处理实时搜索
        function handleRealTimeSearch() {
            // 如果当前没有数据，不执行过滤
            if (currentData.length === 0) return;

            let stockSearchText = document.getElementById('stockCodeOrName').value.trim().toLowerCase();
            let gainianSearchText = document.getElementById('gainian').value.trim().toLowerCase();
            const rows = document.querySelectorAll('#dataTableBody tr');
            let visibleCount = 0;

            if (stockSearchText==="="){
                stockSearchText = flowStock;
            }

            if (stockSearchText==="+"){
                stockSearchText = allOptional;
            }

            if (gainianSearchText==="="){
                gainianSearchText = flowGainian;
            }

            // 过滤逻辑
            currentData.forEach((item, index) => {
                const row = rows[index];
                if (!row) return;

                let isStockMatch = true;
                let isGainianMatch = true;

                // 股票代码/名称过滤
                if (stockSearchText) {
                    const stockCodeMatch = item.stockCode?.toLowerCase().includes(stockSearchText) || false;
                    const stockNameMatch = item.stockName?.toLowerCase().includes(stockSearchText) || false;

                    const stockConcept = item.stockCode+' '+item.stockName ;
                    const searchTerms = stockSearchText.toLowerCase()
                        .split(',')
                        .map(term => term.trim())
                        .filter(Boolean); // 过滤空字符串

                    const allMatch = searchTerms.some(term => stockConcept.includes(term));
                    isStockMatch = stockCodeMatch || stockNameMatch || allMatch;
                }

                // 板块概念过滤
                if (gainianSearchText) {
                    const stockConcept = item.gainians+' '+item.limitUpReason ;//== null ? "--" : stock.concept.toLowerCase();
                    const searchTerms = gainianSearchText.toLowerCase()
                        .split(',')
                        .map(term => term.trim())
                        .filter(Boolean); // 过滤空字符串

                    // 判断是否有任何一个搜索词存在于概念列表中
                    isGainianMatch = searchTerms.some(term => stockConcept.includes(term));

                    // const GainianMatch = item.gainians?.toLowerCase().includes(gainianSearchText) || false;
                    // const limitUpReasonMatch = item.limitUpReason?.toLowerCase().includes(gainianSearchText) || false;
                    // isGainianMatch = GainianMatch || limitUpReasonMatch;
                }

                // 同时满足两个条件才显示
                if (isStockMatch && isGainianMatch) {
                    row.style.display = '';
                    visibleCount++;
                } else {
                    row.style.display = 'none';
                }
            });
            // 更新结果计数
            updateSearchResultCount(visibleCount);
        }

        // 更新搜索结果计数
        function updateSearchResultCount(visibleCount) {
            // 更新分页信息
            const info = document.getElementById('paginationInfo');
            if (info) {
                const start = currentPage * parseInt(document.getElementById('pageSize').value) + 1;
                info.textContent = `筛选结果：共 ${visibleCount} 条（总 ${totalElements} 条）`;
            }
        }

        // 初始化下拉选择框
        function initializeSelects() {
            // 加载涨停类型选项
            fetch('/limitup/api/types')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('limitUpType');
                        data.data.forEach(type => {
                            const option = document.createElement('option');
                            option.value = type;
                            option.textContent = type;
                            select.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('加载涨停类型失败:', error));

            // 加载几天几板选项
            fetch('/limitup/api/consecutive-days')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('consecutiveDays');
                        data.data.forEach(option => {
                            const optionElement = document.createElement('option');
                            optionElement.value = option;
                            optionElement.textContent = option;
                            select.appendChild(optionElement);
                        });
                    }
                })
                .catch(error => console.error('加载几天几板选项失败:', error));
        }

        // 设置默认日期（最近7天）
        function setDefaultDates() {
            const today = new Date();
            const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

            document.getElementById('endDate').value = today.toISOString().split('T')[0];
            document.getElementById('startDate').value = weekAgo.toISOString().split('T')[0];
        }

        // 初始化排序功能
        function initializeSorting() {
            const sortableHeaders = document.querySelectorAll('.sortable');
            sortableHeaders.forEach(header => {
                header.addEventListener('click', function() {
                    const sortField = this.getAttribute('data-sort');
                    handleSort(sortField);
                });
            });
        }

        // 处理排序
        function handleSort(field) {
            if (currentData.length === 0) return;

            // 确定排序方向
            let direction = 'asc';
            if (currentSort.field === field) {
                if (currentSort.direction === 'asc') {
                    direction = 'desc';
                } else if (currentSort.direction === 'desc') {
                    direction = null; // 取消排序
                } else {
                    direction = 'asc';
                }
            }

            // 更新排序状态
            currentSort.field = direction ? field : null;
            currentSort.direction = direction;

            // 执行排序
            if (direction) {
                const sortedData = [...currentData].sort((a, b) => sortData(a, b, field, direction));
                displaySortedData(sortedData);
            } else {
                // 恢复原始顺序
                displaySortedData(currentData);
            }

            // 更新UI
            updateSortUI(field, direction);
        }

        // 数据排序逻辑
        function sortData(a, b, field, direction) {
            // 统一处理排序方向（忽略大小写）
            const isDesc = String(direction).toLowerCase() === 'desc';

            // 字段处理配置：映射字段到对应的取值逻辑
            const fieldConfig = {
                currentPrice: (obj) => parseFloat(obj.currentPrice) || 0,
                priceIncreasePercent: (obj) => parseFloat(obj.priceIncreasePercent) || 0,
                limitUpOrderVolume: (obj) => parseFloat(obj.limitUpOrderVolume) || 0,
                rankPosition: (obj) => parseInt(obj.rankPosition) || 999999, // 空值排最后
                consecutiveLimitUpCount: (obj) => parseInt(obj.consecutiveLimitUpCount) || 0,
                consecutiveLimitUpDays: (obj) => parseInt(obj.consecutiveLimitUpDays) || 0,
                mainCapitalFlow: (obj) => parseInt(obj.mainCapitalFlow) || 0,
                // 处理日期（检查是否为有效日期）
                finalLimitUpTime: (obj) => {
                    const date = new Date(obj.finalLimitUpTime);
                    return !isNaN(date.getTime()) ? date.getTime() : 0;
                },
                firstLimitUpTime: (obj) => {
                    const date = new Date(obj.firstLimitUpTime);
                    return !isNaN(date.getTime()) ? date.getTime() : 0;
                },
                // 字符串字段（空值排最后）
                stockCode: (obj) => obj.stockCode || '',
                stockName: (obj) => obj.stockName || '',
                limitUpReason: (obj) => obj.limitUpReason || '',
                gainians: (obj) => obj.gainians || '',
                limitUpType: (obj) => obj.limitUpType || ''
            };

            // 获取当前字段的处理函数，默认返回0（不排序）
            const getValue = fieldConfig[field];
            if (!getValue) return 0;

            const valueA = getValue(a);
            const valueB = getValue(b);

            // 根据类型选择比较方式
            if (typeof valueA === 'string' && typeof valueB === 'string') {
                // 字符串比较（支持国际化排序）
                const compareResult = valueA.localeCompare(valueB, undefined, { sensitivity: 'base' });
                return isDesc ? -compareResult : compareResult;
            } else {
                // 数字/时间戳比较
                return isDesc ? valueB - valueA : valueA - valueB;
            }
        }


        // 显示排序后的数据
        function displaySortedData(data) {
            const tbody = document.getElementById('dataTableBody');
            tbody.innerHTML = '';

            data.forEach(item => {
                const row = createTableRow(item);
                tbody.appendChild(row);
            });
        }

        // 更新排序UI状态
        function updateSortUI(field, direction) {
            // 清除所有排序状态
            const sortableHeaders = document.querySelectorAll('.sortable');
            sortableHeaders.forEach(header => {
                header.classList.remove('sort-asc', 'sort-desc');
            });

            // 设置当前排序状态
            if (field && direction) {
                const currentHeader = document.querySelector(`[data-sort="${field}"]`);
                if (currentHeader) {
                    currentHeader.classList.add(`sort-${direction}`);
                }
            }
        }

        // 表单提交处理
        document.getElementById('searchForm').addEventListener('submit', function(e) {
            e.preventDefault();
            currentPage = 0;
            alllimitstock = '';
            searchData();
        });

        // 查询数据
        function searchData(page = 0) {
            const formData = new FormData(document.getElementById('searchForm'));
            const params = new URLSearchParams();

            for (let [key, value] of formData.entries()) {
                if (value) {
                    params.append(key, value);
                }
            }

            params.append('page', page);
            params.append('size', document.getElementById('pageSize').value);

            showLoading();

            fetch('/limitup/api/search?' + params.toString())
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        flowStock = data.flowStock;
                        allOptional = data.allOptional;
                        flowGainian = data.flowGainian;
                        revGainian = data.revGainian;
                        displayData(data);
                        updatePagination(data);
                        // 搜索后触发一次过滤（处理可能的初始输入）
                        handleRealTimeSearch();
                    } else {
                        showError(data.message || '查询失败');
                    }
                })
                .catch(error => {
                    console.error('查询失败:', error);
                    showError('网络错误，请稍后重试');
                });
        }

        // 显示数据
        function displayData(data) {
            const tbody = document.getElementById('dataTableBody');
            tbody.innerHTML = '';

            if (data.data && data.data.length > 0) {
                // 保存当前数据用于排序
                currentData = data.data;
                // 清除之前的排序状态
                currentSort = { field: null, direction: null };
                updateSortUI(null, null);

                data.data.forEach(item => {
                    const row = createTableRow(item);
                    tbody.appendChild(row);
                });
                document.getElementById('paginationContainer').style.display = 'flex';

                // 显示汇总统计
                // displaySummary(data.data);
                document.getElementById('summarySection').style.display = 'block';
            } else {
                currentData = [];
                tbody.innerHTML = '<tr><td colspan="19" class="no-data"><i class="bi bi-inbox"></i> 暂无数据</td></tr>';
                document.getElementById('paginationContainer').style.display = 'none';
                document.getElementById('summarySection').style.display = 'none';
            }
        }

        // 显示汇总统计
        function displaySummary(data) {
            const summaryContent = document.getElementById('summaryContent');
            summaryContent.innerHTML = '';

            // 统计涨停原因（按+拆分）
            const reasonStats = {};
            const reasonStocks = {}; // 保存每个原因对应的股票
            let totalStockCount = data.length;
            let totalReasonCount = 0;

            data.forEach(item => {
                const reasonText = item.limitUpReason || '未知原因';
                // 按+拆分原因
                const reasons = reasonText.split('+')
                    .map(reason => reason.trim())
                    .filter(reason => reason.length > 0);

                // 如果没有有效原因，使用"未知原因"
                if (reasons.length === 0) {
                    reasons.push('未知原因');
                }

                // 统计每个拆分后的原因
                reasons.forEach(reason => {
                    reasonStats[reason] = (reasonStats[reason] || 0) + 1;
                    if (!reasonStocks[reason]) {
                        reasonStocks[reason] = [];
                    }
                    reasonStocks[reason].push(item);
                    totalReasonCount++;
                });
            });

            // 按数量排序
            const sortedReasons = Object.entries(reasonStats)
                .sort((a, b) => b[1] - a[1]);

            // 创建总计卡片（显示股票数和原因数）
            const totalCard = createTotalSummaryCard(totalStockCount, totalReasonCount, data);
            summaryContent.appendChild(totalCard);

            // 创建各原因统计卡片
            sortedReasons.forEach(([reason, count]) => {
                const percentage = ((count / totalReasonCount) * 100).toFixed(1);
                const card = createSummaryCard(reason, count, percentage, reasonStocks[reason]);
                summaryContent.appendChild(card);
            });
        }

        // 创建总计汇总卡片
        function createTotalSummaryCard(stockCount, reasonCount, allStocks) {
            const col = document.createElement('div');
            col.className = 'col-lg-3 col-md-4 col-sm-6';

            col.innerHTML = `
                <div class="summary-item total-summary clickable">
                    <div class="summary-reason">总计</div>
                    <div class="summary-count">
                        ${stockCount}只股票
                    </div>
                    <div class="summary-percentage">
                        ${reasonCount}个原因
                    </div>
                </div>
            `;

            // 添加点击事件，显示全部股票
            col.addEventListener('click', function() {
                displayStocks(allStocks);
            });

            return col;
        }

        // 创建汇总统计卡片
        function createSummaryCard(reason, count, percentage, stocks) {
            const col = document.createElement('div');
            col.className = 'col-lg-3 col-md-4 col-sm-6';

            const truncatedReason = reason.length > 12 ? reason.substring(0, 12) + '...' : reason;

            col.innerHTML = `
                <div class="summary-item clickable" title="${reason}">
                    <div class="summary-reason">${truncatedReason}</div>
                    <div class="summary-count">
                        ${count}
                        <span class="summary-percentage">(${percentage}%)</span>
                    </div>
                </div>
            `;

            // 添加点击事件
            col.addEventListener('click', function() {
                displayStocks(stocks);
            });

            return col;
        }

        // 首先提取样式判断逻辑为独立函数，增强可读性和复用性
        function getStockNameStyle1(item) {
            // 先判断是否为allOptional，优先级更高
            if (allOptional && allOptional.split(',').includes(item.stockCode)) {
                return 'background-color: #FF0000;';
            }
            // 再判断是否为flowStock
            if (flowStock && flowStock.split(',').includes(item.stockCode)) {
                return 'background-color: #FFFF00;';
            }
            // 默认无特殊样式
            return '';
        }

        let alllimitstock = '';
        // 创建表格行
        function createTableRow(item) {
            // alert(item);
            const row = document.createElement('tr');
            alllimitstock += item.stockCode+",";
            const formatTime = (timeStr) => {
                if (!timeStr) return '-';
                return new Date(timeStr).toLocaleString('zh-CN');
            };

            const formatTimeMD = (timeStr) => {
                if (!timeStr) return '-';
                const date = new Date(timeStr);
                // 月份从0开始，需要+1
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0'); // 新增秒数处理
                // 格式化为 "月-日 时:分:秒" 形式，例如 "09-07 15:30:45"
                return `${month}-${day} ${hours}:${minutes}:${seconds}`;
            };

            const formatNumber = (num) => {
                if (num === null || num === undefined) return '-';
                return num.toLocaleString();
            };

            const formatDecimal = (num, digits = 2) => {
                if (num === null || num === undefined) return '-';
                return Number(num).toFixed(digits);
            };

            // 热度
            const hotCell = $('<td>');
            const hotText1 = item.rankPosition+"|"+item.oldRankPosition+"|";
            const hotText = (item.oldRankPosition-item.rankPosition) || '-';
            // const hotClass = (item.oldRankPosition-item.rankPosition) >0 ? 'type-badge type-4 color:red':"type-badge type-2 color:green";
            const hotClass = (item.oldRankPosition - item.rankPosition) > 0
                ? 'type-badge type-4 text-red'
                : 'type-badge type-2 text-green';
            const hotBadge1 = $('<span>').text(hotText1 || '未知');
            const hotBadge = $('<span>').addClass(hotClass).text(hotText || '未知');
            hotCell.append(hotBadge1);
            hotCell.append(hotBadge);

            // 资金流向
            const hotflowCell = $('<td>');
            const hotfmlowText = formatDecimal(item.mainCapitalFlow/10000/10000)+"|";//+"|"+formatDecimal(item.capitalFlow/10000/10000);//+"|"+(item.mainCapitalFlow+item.capitalFlow) || '-';
            const hotfmlowClass = formatDecimal(item.mainCapitalFlow/10000/10000)> 0 ? 'text-red' : 'text-green';
            const hotflowText = formatDecimal(item.capitalFlow/10000/10000);//+"|"+formatDecimal(item.capitalFlow/10000/10000);//+"|"+(item.mainCapitalFlow+item.capitalFlow) || '-';
            const hotflowClass = formatDecimal(item.capitalFlow/10000/10000)> 0 ? 'text-red' : 'text-green';
            const hotfmlowBadge = $('<span>').addClass(hotfmlowClass).text(hotfmlowText);
            const hotflowBadge = $('<span>').addClass(hotflowClass).text(hotflowText);
            hotflowCell.append(hotfmlowBadge);
            hotflowCell.append(hotflowBadge);

            // <td style="${flowStock && flowStock.includes(item.stockCode) ? 'background-color: #FFFF00;' : ''}">
            //     <span className="stock-name">${item.stockName || '-'}</span>
            // </td>

            // <td style="${getStockNameStyle1(item)}">
            //     <span class="stock-name">${item.stockName || '-'}</span>
            // </td>
            row.innerHTML = `
                <td><input type="checkbox" class="row-checkbox" name="select-stockCode" value="${item.stockCode || ''}" data-id="${item.stockCode || ''}"></td>
                <td><span class="stock-code" onclick="openSelectedStockCodes('${item.stockCode}')">${item.stockCode || '-'}</span></td>
                <td  style="${getStockNameStyle1(item)}" >
                    <span class="stock-name" onclick="openSelectedStockCodes('${item.stockCode}')">${item.stockName || '-'}</span>
                </td>

                <td class="price-positive">${formatDecimal(item.currentPrice)}</td>
                <td class="price-positive">+${formatDecimal(item.priceIncreasePercent)}</td>
                <td>${formatTimeMD(item.firstLimitUpTime)}</td>
                <td>${formatTimeMD(item.finalLimitUpTime)}</td>
                <td title="${item.limitUpReason || '-'}">${(item.limitUpReason || '-').substring(0, 12)}${(item.limitUpReason || '').length > 12 ? '...' : ''}</td>
                <td title="${item.gainians || '-'}">${(item.gainians || '-').substring(0, 8)}${(item.gainians || '').length > 8 ? '...' : ''}</td>
                <td>${formatDecimal(item.limitUpOrderVolume/10000)}</td>
                <td>${formatDecimal(item.sealOrderAmount/10000/10000)}</td>
                <td>${formatDecimal(item.sealTurnoverRatio)}</td>
                <td>${formatDecimal(item.sealCirculationRatio)}</td>
                <td>${item.openBoardCount || 0}</td>
                <td><span class="consecutive-days">${item.consecutiveLimitUpCount || '-'}</span></td>
                <td><span class="consecutive-limit-up-days">${item.consecutiveLimitUpDays || '-'}</span></td>
                <td title="${item.limitUpType || '-'}">${(item.limitUpType || '-').substring(0, 12)}${(item.limitUpType || '').length > 12 ? '...' : ''}</td>
                <td>${formatTimeMD(item.recordTime)}</td>
            `;
            $(row).append(hotCell);
            // $(row).append(hotflowCell);
            return row;
        }

        // <td><span className="limit-up-type">${item.limitUpType || '-'}</span></td>

        // 实现复制功能
        // // jQuery实现方式
        function getSelectedStockCodesJQ() {
            let selectCode = $('input[name="select-stockCode"]:checked').map(function() {
                return $(this).val();
            }).get().join(',');
            copyStockCodes(selectCode);
        }

        // 全选/取消全选功能实现
        function setupCheckboxHandler() {
            // 获取全选复选框元素
            const selectAllCheckbox = document.getElementById('select-all');

            // 获取所有行复选框
            const rowCheckboxes = document.querySelectorAll('input[name="select-stockCode"]');

            // 全选复选框变更事件
            selectAllCheckbox.addEventListener('change', function() {
                // 将所有行复选框的状态设置为与全选复选框一致
                rowCheckboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });

            // 监听行复选框的变化，更新全选框状态
            rowCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function() {
                    // 检查所有行复选框是否都被选中
                    const allChecked = Array.from(rowCheckboxes).every(cb => cb.checked);
                    selectAllCheckbox.checked = allChecked;
                });
            });
        }


        $(document).ready(function() {
            // 为表格行绑定点击事件
            $('table').on('click', 'tr', function(e) {
                // 排除直接点击复选框的情况
                if($(e.target).is('input[type="checkbox"]')) return;

                // 获取当前行的复选框
                var $checkbox = $(this).find('.row-checkbox');

                // 切换选中状态
                $checkbox.prop('checked', !$checkbox.prop('checked'));

                // 可选：添加行高亮样式
                $(this).toggleClass('active', $checkbox.prop('checked'));
            });
        });

        function addupdateFocusStocks() {
            var focusStocks = $('input[name="select-stockCode"]:checked').map(function() {
                return $(this).val();
            }).get().join(',');

            if (!focusStocks || focusStocks.trim() === '') {
                alert('没有选择股票代码');
                return;
            }

            focusStocks=(focusStocks ? focusStocks.split('\n').join(',') : '');
            $.ajax({
                url: '/sysinfo/appendBy',
                method: 'GET',
                data: {
                    focusStocks: focusStocks
                },
                success: function (response) {
                    alert('关注成功');
                },
                error: function (xhr, status, error) {
                    console.error('概念查询失败:', error);
                    $('#loadingIndicator').removeClass('active');
                    reject(error);
                }
            });
        }

        function removeupdateFocusStock() {
            var focusStocks = $('input[name="select-stockCode"]:checked').map(function() {
                return $(this).val();
            }).get().join(',');

            if (!focusStocks || focusStocks.trim() === '') {
                alert('没有选择股票代码');
                return;
            }

            focusStocks=(focusStocks ? focusStocks.split('\n').join(',') : '');
            $.ajax({
                url: '/sysinfo/removeBy',
                method: 'GET',
                data: {
                    focusStocks: focusStocks
                },
                success: function (response) {
                    alert('取消关注成功');
                },
                error: function (xhr, status, error) {
                    console.error('概念查询失败:', error);
                    $('#loadingIndicator').removeClass('active');
                    reject(error);
                }
            });
        }


        function copyallstock() {
            let trimmedStr = alllimitstock.replace(/a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, '');
            copyStockCodes(trimmedStr);
        }

        // 更新分页
        function updatePagination(data) {
            currentPage = data.currentPage;
            totalPages = data.totalPages;
            totalElements = data.totalElements;

            const highlightedGains = processAndHighlightGains(data, revGainian);
            $('#allHOTGainian').html(highlightedGains);
            // $('#allHOTGainian').val(data.allGainian);

            // 更新分页信息
            const info = document.getElementById('paginationInfo');
            const start = currentPage * data.pageSize + 1;
            const end = Math.min((currentPage + 1) * data.pageSize, totalElements);
            info.textContent = `显示 ${start}-${end} 条，共 ${totalElements} 条记录`;

            // 更新分页按钮
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';

            // 上一页
            const prevLi = document.createElement('li');
            prevLi.className = `page-item ${currentPage === 0 ? 'disabled' : ''}`;
            prevLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>`;
            pagination.appendChild(prevLi);

            // 页码
            const startPage = Math.max(0, currentPage - 2);
            const endPage = Math.min(totalPages - 1, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const li = document.createElement('li');
                li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i + 1}</a>`;
                pagination.appendChild(li);
            }

            // 下一页
            const nextLi = document.createElement('li');
            nextLi.className = `page-item ${currentPage === totalPages - 1 ? 'disabled' : ''}`;
            nextLi.innerHTML = `<a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>`;
            pagination.appendChild(nextLi);
        }

        // 处理概念数据并高亮显示
        function processAndHighlightGains(data, revGainian) {
            if (!data || !data.allGainian) {
                return '';
            }

            // 处理revGainian为Set便于快速查找
            const revGainianSet = new Set();
            if (revGainian && revGainian.trim() !== '') {
                revGainian.split(',').forEach(item => {
                    revGainianSet.add(item.trim());
                });
            }

            // 按分号分割概念数组（保留原始格式）
            const gainArray = data.allGainian.split(';')
                .map(item => item.trim())
                .filter(item => item !== '');

            // 构建带高亮的HTML
            let highlightedHtml = '';
            gainArray.forEach((gain, index) => {
                // 提取[]前面的概念名称（用于匹配判断）
                const conceptName = gain.replace(/\[.*?\]/g, '').trim();

                // 检查是否需要高亮
                if (revGainianSet.has(conceptName)) {
                    highlightedHtml += `<span style="color: red; font-weight: bold;">${gain}</span>`;
                } else {
                    highlightedHtml += `<span>${gain}</span>`;
                }

                // 添加分隔符（最后一个元素不添加）
                if (index < gainArray.length - 1) {
                    highlightedHtml += '; ';
                }
            });

            return highlightedHtml;
        }

        // 显示指定股票列表
        function displayStocks(stocks) {
            const tbody = document.getElementById('dataTableBody');
            tbody.innerHTML = '';

            // 保存当前数据用于排序
            currentData = stocks;
            // 清除之前的排序状态
            currentSort = { field: null, direction: null };
            updateSortUI(null, null);

            stocks.forEach(item => {
                const row = createTableRow(item);
                tbody.appendChild(row);
            });

            // 滚动到表格位置
            document.querySelector('.result-table').scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });

            // 更新分页信息（显示筛选结果）
            const info = document.getElementById('paginationInfo');
            info.textContent = `显示筛选结果：共 ${stocks.length} 条记录`;
            document.getElementById('paginationContainer').style.display = 'flex';

            // 隐藏分页按钮（因为是筛选结果）
            document.getElementById('pagination').innerHTML = '';
        }

        // 切换页面
        function changePage(page) {
            if (page >= 0 && page < totalPages && page !== currentPage) {
                searchData(page);
            }
        }

        // 获取今日涨停数据
        function getTodayData() {
            alllimitstock = '';
            showLoading();

            fetch('/limitup/api/today')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        flowStock = data.flowStock;
                        allOptional = data.allOptional;
                        flowGainian = data.flowGainian;
                        revGainian = data.revGainian;
                        const mockPageData = {
                            success: true,
                            data: data.data,
                            totalElements: data.count,
                            totalPages: 1,
                            currentPage: 0,
                            pageSize: data.pageSize,
                            allGainian: data.allGainian,
                            hasNext: false,
                            hasPrevious: false
                        };
                        // response.put("allGainian", allGainian);
                        displayData(mockPageData); //不显示
                        updatePagination(mockPageData);

                        // console.log(revGainian);
                        // 搜索后触发一次过滤
                        handleRealTimeSearch();
                    } else {
                        showError(data.message || '获取今日涨停数据失败');
                    }
                })
                .catch(error => {
                    console.error('获取今日涨停数据失败:', error);
                    showError('网络错误，请稍后重试');
                });
        }

        // 重置表单
        function resetForm() {
            alllimitstock = '';
            document.getElementById('searchForm').reset();
            setDefaultDates();
            // 清除数据和排序状态
            currentData = [];
            currentSort = { field: null, direction: null };
            updateSortUI(null, null);
            document.getElementById('dataTableBody').innerHTML = '<tr><td colspan="19" class="loading"><i class="bi bi-hourglass-split"></i> 请输入查询条件并点击查询</td></tr>';
            document.getElementById('paginationContainer').style.display = 'none';
            document.getElementById('summarySection').style.display = 'none';
            document.getElementById('dailySummarySection').style.display = 'none';
        }

        // 显示加载状态
        function showLoading() {
            currentData = [];
            currentSort = { field: null, direction: null };
            updateSortUI(null, null);
            document.getElementById('dataTableBody').innerHTML = '<tr><td colspan="19" class="loading"><i class="bi bi-hourglass-split"></i> 查询中...</td></tr>';
            document.getElementById('paginationContainer').style.display = 'none';
            document.getElementById('summarySection').style.display = 'none';
        }

        // 显示错误信息
        function showError(message) {
            currentData = [];
            currentSort = { field: null, direction: null };
            updateSortUI(null, null);
            document.getElementById('dataTableBody').innerHTML = `<tr><td colspan="19" class="no-data"><i class="bi bi-exclamation-triangle text-warning"></i> ${message}</td></tr>`;
            document.getElementById('paginationContainer').style.display = 'none';
            document.getElementById('summarySection').style.display = 'none';
        }

        // 切换汇总统计的显示状态
        function toggleSummary() {
            // const summaryBody = document.getElementById('summaryBody');
            // const summaryToggleIcon = document.getElementById('summaryToggleIcon');
            //
            // if (summaryBody.style.display === 'none' || summaryBody.style.display === '') {
            //     summaryBody.style.display = 'block';
            //     summaryToggleIcon.className = 'bi bi-chevron-up';
            // } else {
            //     summaryBody.style.display = 'none';
            //     summaryToggleIcon.className = 'bi bi-chevron-down';
            // }
        }

        // 切换每日汇总显示状态
        function toggleDailySummarySection() {
            // const dailySummaryBody = document.getElementById('dailySummaryBody');
            // const dailySummaryToggleIcon = document.getElementById('dailySummaryToggleIcon');
            //
            // if (dailySummaryBody.style.display === 'none' || dailySummaryBody.style.display === '') {
            //     dailySummaryBody.style.display = 'block';
            //     dailySummaryToggleIcon.className = 'bi bi-chevron-up';
            // } else {
            //     dailySummaryBody.style.display = 'none';
            //     dailySummaryToggleIcon.className = 'bi bi-chevron-down';
            // }
        }

        // 获取每日汇总数据
        function getDailySummary() {
            alllimitstock = '';
            const formData = new FormData(document.getElementById('searchForm'));
            const params = new URLSearchParams();

            for (let [key, value] of formData.entries()) {
                if (value && key !== 'pageSize') { // 排除pageSize，获取全部数据
                    params.append(key, value);
                }
            }

            // 设置大的页面大小以获取所有数据
            params.append('page', 0);
            params.append('size', 10000);

            showDailySummaryLoading();

            // 获取今天的日期
            const today = new Date().toISOString().split('T')[0];
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            // 判断查询范围是否包含今天
            const includestoday = (!endDate || endDate >= today) && (!startDate || startDate <= today);

            // 创建Promise数组来并行获取数据
            const promises = [];

            // 1. 获取历史数据（排除今天）
            if (startDate && endDate) {
                let historyEndDate = endDate;
                if (includestoday && endDate >= today) {
                    // 如果查询范围包含今天，则历史数据查询到昨天为止
                    const yesterday = new Date();
                    yesterday.setDate(yesterday.getDate() - 1);
                    historyEndDate = yesterday.toISOString().split('T')[0];
                }

                // 只有当开始日期不晚于历史结束日期时才查询历史数据
                if (startDate <= historyEndDate) {
                    const historyParams = new URLSearchParams(params);
                    historyParams.set('endDate', historyEndDate);
                    promises.push(
                        fetch('/limitup/api/search?' + historyParams.toString())
                            .then(response => response.json())
                            .then(data => ({ type: 'history', data: data.success ? data.data : [] }))
                    );
                } else {
                    promises.push(Promise.resolve({ type: 'history', data: [] }));
                }
            } else {
                promises.push(Promise.resolve({ type: 'history', data: [] }));
            }

            // 2. 获取今日数据（如果查询范围包含今天）
            if (includestoday) {
                // 优先从数据库获取今日数据，如果没有再从接口获取
                const todayDataPromise = new Promise((resolve) => {
                    // 先尝试从数据库获取今日数据
                    const todayParams = new URLSearchParams(params);
                    todayParams.set('startDate', today);
                    todayParams.set('endDate', today);

                    fetch('/limitup/api/search?' + todayParams.toString())
                        .then(response => response.json())
                        .then(data => {
                            if (data.success && data.data && data.data.length > 0) {
                                // 数据库有今日数据，直接使用
                                resolve({ type: 'today', data: data.data });
                            } else {
                                // 数据库没有今日数据，从接口获取
                                fetch('/limitup/api/today')
                                    .then(response => response.json())
                                    .then(apiData => {
                                        resolve({ type: 'today', data: apiData.success ? apiData.data : [] });
                                    })
                                    .catch(() => {
                                        resolve({ type: 'today', data: [] });
                                    });
                            }
                        })
                        .catch(() => {
                            // 数据库查询失败，尝试从接口获取
                            fetch('/limitup/api/today')
                                .then(response => response.json())
                                .then(apiData => {
                                    resolve({ type: 'today', data: apiData.success ? apiData.data : [] });
                                })
                                .catch(() => {
                                    resolve({ type: 'today', data: [] });
                                });
                        });
                });

                promises.push(todayDataPromise);
            } else {
                promises.push(Promise.resolve({ type: 'today', data: [] }));
            }

            // 并行执行所有请求
            Promise.all(promises)
                .then(results => {
                    const historyData = results.find(r => r.type === 'history')?.data || [];
                    const todayData = results.find(r => r.type === 'today')?.data || [];

                    // 为今日数据添加今天的日期标识
                    const todayWithDate = todayData.map(item => ({
                        ...item,
                        recordTime: item.recordTime || new Date().toISOString()
                    }));

                    // 合并数据
                    const allData = [...historyData, ...todayWithDate];

                    if (allData.length > 0) {
                        displayDailySummary(allData);
                    } else {
                        showDailySummaryError('暂无数据');
                    }
                })
                .catch(error => {
                    console.error('获取每日汇总失败:', error);
                    showDailySummaryError('网络错误，请稍后重试');
                });
        }

        // 显示每日汇总数据
        function displayDailySummary(data) {
            if (!data || data.length === 0) {
                showDailySummaryError('暂无数据');
                return;
            }

            // 按日期分组数据
            const dailyData = {};
            data.forEach(item => {
                // 提取日期部分（去掉时间）
                const dateStr = item.recordTime ? item.recordTime.split('T')[0] : '未知日期';
                if (!dailyData[dateStr]) {
                    dailyData[dateStr] = [];
                }
                dailyData[dateStr].push(item);
            });

            // 按日期排序（最新的在前面）
            // const sortedDates = Object.keys(dailyData).sort((a, b) => new Date(b) - new Date(a));
            // 新升序排序（最早的在前面）
            const sortedDates = Object.keys(dailyData).sort((a, b) => new Date(a) - new Date(b));

            const dailySummaryContent = document.getElementById('dailySummaryContent');
            dailySummaryContent.innerHTML = '';

            // 根据天数决定使用自适应宽度还是固定宽度
            const useAutoWidth = sortedDates.length <= 7;

            sortedDates.forEach((date, index) => {
                const dayData = dailyData[date];
                console.log("dayData=="+dayData);
                const dailyCard = createDailySummaryCard(date, dayData, index, useAutoWidth);
                dailySummaryContent.appendChild(dailyCard);
            });

            // 显示每日汇总区域
            document.getElementById('dailySummarySection').style.display = 'block';
        }

        // 创建每日汇总卡片
        function createDailySummaryCard(date, dayData, index, useAutoWidth) {
            const cardDiv = document.createElement('div');
            cardDiv.className = `daily-summary-item ${useAutoWidth ? 'auto-width' : 'fixed-width'}`;

            // 统计该日的涨停原因
            const reasonStats = {};
            const reasonStocks = {};
            let totalReasonCount = 0;

            dayData.forEach(item => {
                const reasonText = item.limitUpReasonGai|| '未知原因';
                const reasons = reasonText.split('+')
                    .map(reason => reason.trim())
                    .filter(reason => reason.length > 0);

                if (reasons.length === 0) {
                    reasons.push('未知原因');
                }

                reasons.forEach(reason => {
                    reasonStats[reason] = (reasonStats[reason] || 0) + 1;
                    if (!reasonStocks[reason]) {
                        reasonStocks[reason] = [];
                    }
                    reasonStocks[reason].push(item);
                    totalReasonCount++;
                });
            });

            // 按数量排序原因
            const sortedReasons = Object.entries(reasonStats)
                .sort((a, b) => b[1] - a[1]);

            // 格式化日期显示
            const formatDate = (dateStr) => {
                const date = new Date(dateStr);
                const today = new Date();
                const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);

                const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

                if (dateStr === today.toISOString().split('T')[0]) {
                    return { text: weekdays[date.getDay()] + ' ' + dateStr.substring(5), isToday: true };
                } else if (dateStr === yesterday.toISOString().split('T')[0]) {
                    return { text: weekdays[date.getDay()] + ' ' + dateStr.substring(5), isToday: false };
                } else {
                    return { text: weekdays[date.getDay()] + ' ' + dateStr.substring(5), isToday: false };
                }
            };

            const dateInfo = formatDate(date);

            // 根据宽度模式调整文本截断长度
            const maxReasonLength = useAutoWidth ? 15 : 20;

            // 提取当天所有股票代码（去重）
            const allStockCodes = [...new Set(dayData.map(item => item.stockCode).filter(code => code))];

            cardDiv.innerHTML = `
                    <div class="daily-summary-header ${dateInfo.isToday ? 'today' : ''} d-flex align-items-center justify-content-between" style="position: relative;" onclick="toggleDailySummaryCard(${index})">
                        <div class="daily-summary-date flex-shrink-0">${dateInfo.text}</div>
                        <div class="daily-summary-stats d-flex align-items-center gap-3 flex-shrink-0">
                            <span>${dayData.length}只</span>
                            <i class="bi bi-chevron-up expand-icon rotated" id="dailyToggleIcon${index}"></i>
                        </div>
                        ${dateInfo.isToday ? '<div style="position: absolute; top: 6px; right: 6px;"><span class="badge bg-light text-success" style="font-size: 9px;">实时</span></div>' : ''}
                    </div>

                </div>
                <div class="daily-summary-content show" id="dailyContent${index}">
                    <div class="daily-reason-item" style="background: #e3f2fd; border-bottom: 2px solid #1976d2;" onclick="copyStockCodes('${allStockCodes.join(',')}')" title="复制当天所有股票代码">
                        <div class="daily-reason-text" style="color: #1976d2; font-weight: 600;">
                            <i class="bi bi-clipboard"></i> 复制所有代码
                        </div>
                        <div class="daily-reason-count" style="background: #1976d2;">${allStockCodes.length}</div>
                    </div>
                    ${sortedReasons.map(([reason, count]) => {
                        const truncatedReason = reason.length > maxReasonLength ? reason.substring(0, maxReasonLength) + '...' : reason;
                        // 修改点击事件，添加reason参数
                        return `
                            <div class="daily-reason-item"
                                 onclick="displayStocksWithHighlight(${JSON.stringify(reasonStocks[reason]).replace(/"/g, '&quot;')}, '${reason.replace(/'/g, "\\'")}')">
                                <div class="daily-reason-text" title="${reason}">${truncatedReason}</div>
                                <div class="daily-reason-count">${count}</div>
                            </div>
                        `;
                    }).join('')}
                </div>
            `;

            return cardDiv;
        }

        // 添加新函数处理带高亮的显示
        function displayStocksWithHighlight(stocks, reason) {
            // 先清除所有之前的高亮
            clearAllHighlights();

            // 显示选中的股票
            displayStocks(stocks);

            // 高亮所有相同的原因
            highlightSameReasons(reason);
        }

        // 清除所有高亮
        function clearAllHighlights() {
            document.querySelectorAll('.daily-reason-item.highlighted')
                .forEach(item => item.classList.remove('highlighted'));
        }

        // 高亮所有相同的原因
        function highlightSameReasons(targetReason) {
            // 转义特殊字符，确保选择器能正确匹配
            const escapedReason = targetReason.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

            // 查找所有包含相同原因的元素并高亮
            document.querySelectorAll('.daily-reason-text[title]')
                .forEach(textElement => {
                    // 使用title属性进行精确匹配
                    if (textElement.getAttribute('title') === targetReason) {
                        textElement.closest('.daily-reason-item').classList.add('highlighted');
                    }
                });
        }


        // 切换每日汇总卡片的展开状态
        function toggleDailySummaryCard(index) {
            const content = document.getElementById(`dailyContent${index}`);
            const icon = document.getElementById(`dailyToggleIcon${index}`);

            if (content.classList.contains('show')) {
                content.classList.remove('show');
                icon.className = 'bi bi-chevron-down expand-icon';
            } else {
                content.classList.add('show');
                icon.className = 'bi bi-chevron-up expand-icon rotated';
            }
        }

        // 显示每日汇总加载状态
        function showDailySummaryLoading() {
            const dailySummaryContent = document.getElementById('dailySummaryContent');
            dailySummaryContent.innerHTML = `
                <div class="text-center py-4">
                    <i class="bi bi-hourglass-split"></i> 正在加载每日汇总...
                </div>
            `;
            document.getElementById('dailySummarySection').style.display = 'block';
        }

        // 显示每日汇总错误信息
        function showDailySummaryError(message) {
            const dailySummaryContent = document.getElementById('dailySummaryContent');
            dailySummaryContent.innerHTML = `
                <div class="text-center py-4 text-muted">
                    <i class="bi bi-exclamation-triangle"></i> ${message}
                </div>
            `;
        }

        // 复制股票代码到剪贴板
        function copyStockCodes(stockCodes) {
            // 阻止事件冒泡，避免触发父元素的点击事件
            event.stopPropagation();

            if (!stockCodes || stockCodes.trim() === '') {
                alert('没有股票代码可复制');
                return;
            }

            // 使用现代浏览器的剪贴板API
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(stockCodes).then(() => {
                    // 显示成功提示
                    showCopySuccessToast(stockCodes.split(',').length);
                }).catch(err => {
                    console.error('复制失败:', err);
                    fallbackCopy(stockCodes);
                });
            } else {
                // 降级方案
                fallbackCopy(stockCodes);
            }
        }

        // 降级复制方案
        function fallbackCopy(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                document.execCommand('copy');
                showCopySuccessToast(text.split(',').length);
            } catch (err) {
                console.error('降级复制也失败了:', err);
                alert('复制失败，请手动复制：' + text);
            } finally {
                document.body.removeChild(textArea);
            }
        }

        // 显示复制成功的提示
        function showCopySuccessToast(count) {
            // 创建提示元素
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                z-index: 9999;
                font-size: 12px;
                font-weight: 500;
                display: flex;
                align-items: center;
                gap: 8px;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.3s ease;
            `;

            toast.innerHTML = `
                <i class="bi bi-check-circle-fill"></i>
                已复制 ${count} 个股票代码
            `;

            document.body.appendChild(toast);

            // 动画显示
            setTimeout(() => {
                toast.style.opacity = '1';
                toast.style.transform = 'translateX(0)';
            }, 100);

            // 3秒后自动隐藏
            setTimeout(() => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    if (document.body.contains(toast)) {
                        document.body.removeChild(toast);
                    }
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html>